<template>
    <div class='edit-popup'>
        <popup
            ref='popupRef'
            :title='popupTitle'
            :async='true'
            width='650px'
            @confirm='handleSubmit'
            @close='handleClose'
            :confirm-button-text="formData.isEdit ? '确认编辑' : '确认添加'"
        >
            <el-form
                hide-required-asterisk
                ref='formRef'
                label-position='left'
                :model='formData'
                label-width='80px'
                :rules='formRules'
            >
                <el-form-item label='Day' prop='day'>
                    <el-input v-model='formData.day' clearable placeholder='请输入Day' />
                </el-form-item>
                <el-form-item label='绑定景点' prop='point'>
                    <el-select filterable v-model='formData.point' style='width: 268px;' @change='selectSpotHandle'>
                        <el-option
                            v-for='(item, index) in pointOption'
                            :key='index'
                            :label='item.label'
                            :value='item.value'
                        />
                    </el-select>
                </el-form-item>
                <!--        <el-form-item label="线路名称" prop="line_name">-->
                <!--          <el-input v-model="formData.line_name" clearable placeholder="请输入线路名称"/>-->
                <!--        </el-form-item>-->
                <el-form-item
                    :label='`景点${index + 1}`'
                    v-for='(item, index) in pointKeys'
                    :key='index'
                    :prop='item'
                >
                    <div style='width: 100%;display:flex;flex-flow:row nowrap;gap: 24px;'>
                        <div>
                            <el-time-picker :default-value='defaultTime' value-format='HH:mm'
                                            v-model='formData[item].time' placeholder='请选择游玩时间' />
                            <!--                            <el-date-picker-->
                            <!--                                v-model='formData[item].time'-->
                            <!--                                type='datetime'-->
                            <!--                                placeholder='请选择游玩日期、时间'-->
                            <!--                                value-format='YYYY-MM-DD HH:mm:ss'-->
                            <!--                            />-->
                        </div>
                        <div style='flex: 1;'>
                            <el-input v-model='formData[item].name' clearable placeholder='请输入景点' />
                        </div>
                        <el-button @click='removePoint(item)' type='danger' :icon='Delete' circle />
                    </div>
                </el-form-item>
            </el-form>
            <div class='pop-footer' v-if='formData.point'>
                <el-button @click='addPoint()' style='width: 100%' type='primary' plain>添加景点</el-button>
            </div>
        </popup>
    </div>
</template>

<script lang='ts' setup name='lineSpotRelEdit'>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiLineSpotRelDetail, apiLineSpotRelAdd, apiLineSpotRelEdit } from '@/api/line_spot_rel'
import type { PropType } from 'vue'
import { computed } from 'vue'
import request from '@/utils/request'
import { Delete } from '@element-plus/icons-vue'

const props = defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    },
    lineId: {
        type: String
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')


function initSpotHandle(list: any[]) {
    // 先清除已填写的
    pointKeys.value.forEach(key => {
        removePoint(key)
    })
    if (!list || !list.length) return
    list.forEach((item) => addPoint(item))
}

function selectSpotHandle(id: number) {
    const target = pointOption.value.find(item => item.value === id)
    if (!target) return
    initSpotHandle(target.points)
}


function removePoint(key: string) {
    delete formData[key]
    delete formRules[key]
}

function addPoint(value: any) {
    if (!value) value = { time: '', name: '' }
    const len = pointKeys.value.length
    const key = 'points_' + len
    formData[key] = value
    formRules[key] = getPointValidator()
}

const pointKeys = computed(() => {
    const keys = Object.keys(formData)
    return keys.filter((item) => item.includes('points'))
})
const defaultTime = new Date('2023-12-06 00:00:00')
const selectPoints = computed(() => {
    // const target = pointOption.value.find((item: any) => item.value === formData.point)
    // if (!target) return []
    // return target.points || []

})

const patchZero = (value: number) => {
    return ('0' + value).slice(-2)
}

const timeOption = computed(() => {
    const result = []
    for (let i = 0; i < 24; i++) {
        const label = patchZero(i) + ':00'
        result.push({
            label,
            value: label
        })
    }
    return result
})

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑景点线路管理' : '新增景点线路管理'
})

// 表单数据
const formData = reactive({
    id: '',
    line_name: '',
    value: '',
    day: '',
    line_id: '',
    point: '',
    // points_0: {time: '', name: ''},
    isEdit: false
})

const pointOption = ref([])

async function initPointOpt() {
    const resp = await request.post({
        url: '/LineSpot/getSpot'
    })
    console.warn(resp, 'getSpot')
    if (!resp || !resp.length) return
    pointOption.value = resp.map((item: any) => {
        const { id, name, value } = item
        return {
            label: name,
            value: id,
            points: JSON.parse(value)
        }
    })
    console.log(pointOption.value, 'resp')
}

function getPointValidator() {
    return [
        {
            trigger: 'change',
            validator: (_: any, value: any, callback: any) => {
                console.log(value, 'value')
                const { time, name } = value
                if (!time) return callback(new Error('请选择时间'))
                if (!name) return callback(new Error('请输入名称'))
                callback()
            }
        }
    ]
}

// 表单验证
const formRules = reactive<any>({
    day: [
        {
            required: true,
            message: '请输入第几天'
        }
    ],
    point: [
        {
            required: true,
            message: '请选择景点'
        }
    ]
    // points_0: getPointValidator()
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    const { day, line_name, value, id } = data
    formData.id = id
    formData.point = line_name
    formData.day = day
    formData.isEdit = true
    initSpotHandle(value)
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiLineSpotRelDetail({
        id: row.id
    })
    await initPointOpt()
    console.log(data, '详情2')
    setFormData(data)
}

function getPoints() {
    return pointKeys.value.map((item) => {
        //@ts-ignore
        const { name, time } = formData[item]
        //@ts-ignore : time.slice(0, time.lastIndexOf(':'))
        return { name, time }
    })
}

// 提交按钮
const handleSubmit = async () => {
    formRef.value
        ?.validate()
        .then(async (flag) => {
            const points = getPoints()
            const { line_name, day, point } = formData
            const { lineId } = props
            if (formData.isEdit) {
                await apiLineSpotRelEdit({
                    line_id: lineId,
                    line_name: point,
                    day,
                    points,
                    id: formData.id
                })
                emit('success')
                return emit('close')
            }
            await apiLineSpotRelAdd({
                line_id: lineId,
                line_name: point,
                day,
                points
            })
            emit('success')
            emit('close')
        })
        .catch(() => {
        })
    // await formRef.value?.validate()
    // const data = {...formData,}
    // mode.value == 'edit'
    //     ? await apiLineSpotRelEdit(data)
    //     : await apiLineSpotRelAdd(data)
    // popupRef.value?.close()
    // emit('success')
}

//打开弹窗
const open = (type = 'add', row: any) => {
    mode.value = type
    popupRef.value?.open()
    if (type === 'add') return initPointOpt()
    getDetail(row)
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>

<style scoped lang='scss'>
.add-button {
    padding: 8px 0;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
}

.pop-footer {
    margin-top: 24px;
}
</style>
